﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using StockFinder.Model;

namespace StockFinder.YahooFinance
{
    public class YahooFinanceCsvStockPriceHistoryExtractor
    {
        public List<DailyPrice> GetHistoricPricesFromSource(string source)
        {
            var prices = new List<DailyPrice>();

            if (!string.IsNullOrEmpty(source))
            {
                string[] lines;

                if (source.Contains(Environment.NewLine))
                {
                    lines = source.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                }
                else if (source.Contains("\n"))
                {
                    lines = source.Split(new[] { "\n" }, StringSplitOptions.None);
                }
                else
                {
                    //not sure how to split lines, return empty array
                    lines = new string[] { };
                }

                prices.AddRange(from line in lines
                                where !line.Contains("Date") && !string.IsNullOrEmpty(line)
                                select line.Split(new[] { "," }, StringSplitOptions.None)
                                    into cells
                                    select new DailyPrice
                                    {
                                        PriceDate = Convert.ToDateTime(cells[0]),
                                        Open = Convert.ToDecimal(cells[1]),
                                        High = Convert.ToDecimal(cells[2]),
                                        Low = Convert.ToDecimal(cells[3]),
                                        Close = Convert.ToDecimal(cells[4]),
                                        Volume = Convert.ToDecimal(cells[5]),
                                        AdjustedClose = Convert.ToDecimal(cells[6]),
                                    });
                
            }

            return prices;
        }

        public List<DailyPrice> GetHistoricPrices(string location)
        {
            var prices = new List<DailyPrice>();

            if (File.Exists(location))
            {
                string source;

                using (var sr = new StreamReader(location))
                {
                    source = sr.ReadToEnd();
                }

                prices = GetHistoricPricesFromSource(source);
            }

            return prices;
        }
    }
}

